package com.simplesoftwares.client.library.appstructure.formscreen;

import com.google.code.p.gwtchismes.client.GWTCAlert;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.simplesoftwares.client.library.ReturnFromServer;
import com.simplesoftwares.client.library.appstructure.EntityPresenter;
import com.simplesoftwares.client.library.appstructure.SuperModel;
import com.simplesoftwares.client.library.appstructure.UiScreen;

/**
 * Presenter for Form Screens.
 * @author Kamala
 *
 * @param <T>
 */
public abstract class FormScreenPresenter<T extends SuperModel> extends EntityPresenter<T> {
	
    /**
     * 
     * Reffers to   {@link FormScreen} type screen.This variable actually points to ConcreteScreen.In this design pattern
     * concrete screen will be refferd by three variable </br>
     * 1. ConcreteScreen Type - Concrete Presenter can acess ConcreteScreen level methods.
     * 2. FormScreen Type - {@link FormScreenPresenter} can acess FormScreen level methods.
     * 3. UiScreen Type - {@link EntityPresenter} can acess UiScreen level methods.
     */
	protected FormScreen<T> formview;
	/**
	 * 
	 * @param view Screen for this presenter
	 * @param model Model for this presenter
	 */
	public FormScreenPresenter(UiScreen<T> view, T model) {
		super(view, model);
		formview=(FormScreen<T>) view;
	}
	
	/**
	 * If validation is true validate then saves the model.
	 * To Do:Prone to concurrency failure.
	 * To Do : Pradnya Idaea can be used
	 */

	@Override
	protected void reactOnSave() {
		
		if(validateAndUpdateModel())
		{
			// Async querry is going to start. We do not want user to do any thing untill it completes.
			view.showWaitSymbol();
			service.save(model,new AsyncCallback<ReturnFromServer>() {
				
				@Override
				public void onSuccess(ReturnFromServer result) {
					
					//Async run sucessfully , hide the wait symbol
					view.hideWaitSymbol();
					// set the count returned from server to this model
					model.setCount(result.count);
				   //set the id from server to this model
					model.setId(result.id);
					view.setToViewState();
					//Set count on view
					view.setCount(result.count);
					view.showDialogMessage("Data Successfully Saved !",GWTCAlert.OPTION_ROUNDED_BLUE ,GWTCAlert.OPTION_ANIMATION);
					System.out.println("Model ID "+model.getId());
					
					
				}
				
				@Override
				public void onFailure(Throwable caught) {
					view.hideWaitSymbol();
					view.showDialogMessage("Data Save Unsuccessful! Try again.");
					caught.printStackTrace();
					
				}
			});
			
		}
		
		
	}

	

	
   /**
    * Stub for design side issues.
    */
	@Override
	public void reactOnDownload() {
		
		
	}

}
